//
//  MString+Extention.swift
//  paperPlane
//
//  Created by 极梵软件 on 2021/2/23.
//

import Foundation

extension String{
    
    /// 动态计算字体的Size
    /// - Parameters:
    ///   - font: 字体样式
    ///   - size: 限定的大小
    /// - Returns: 字体大小
    func calculateTextSize(font:UIFont,size:CGSize) ->CGSize{
        
        //动态计算字体宽度
        let rect = self.boundingRect(with: size,
                                     options: [.usesLineFragmentOrigin,
                                               .usesFontLeading,
                                               .truncatesLastVisibleLine],
                                  attributes: [NSAttributedString.Key.font: font] ,
                                     context: nil)
        return rect.size
    }

    /// 生成随机字符串
    /// - Parameters:
    ///   - count: 随机字符串的长度
    /// - Returns: 字符串
    static func random(_ count : Int) -> String{
        let random_str_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        var ranStr = ""
        for _ in 0..<count {
            let index = Int(arc4random_uniform(UInt32(random_str_characters.count)))
            ranStr.append(random_str_characters[random_str_characters.index(random_str_characters.startIndex, offsetBy: index)])
        }
        return ranStr
    }
    
    /// 是否为中文
    /// - Returns: true 中文     false 不是中文
    func isChinese() -> Bool{
        let match: String = "(^[\\u4e00-\\u9fa5]+$)"
        let predicate = NSPredicate(format: "SELF matches %@", match)
        return predicate.evaluate(with: self)
    }
    
    
    /// 判断是否包含有中文
    /// - Returns: true 包含   false 不包含
    func isIncludeChinese() -> Bool {
        
        for element in self{
            if String(element).isChinese(){
                return true
            }
        }
        return false
    }
    
    /// 汉字转拼音
    /// - Returns: 拼音
    func toPinYin()->String{
        let mutableString = NSMutableString(string: self)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let str = String(mutableString)
        return str.replacingOccurrences(of: " ", with: "")
    }
    
    /// 获取首字母的ASCLL值
    /// - Parameter model: 好友model
    /// - Returns: ASCLL值
    func getFistCharacterASCLL()->UInt32?{
        var fistCharacter = String(self[self.startIndex])
        
        //判断是否为中文
        if fistCharacter.isChinese() {
            //转拼音
            fistCharacter = fistCharacter.getPinYinFistStr()
        }
        
        let ascllValue = UnicodeScalar(fistCharacter.lowercased())?.value
        
        return ascllValue
    }
    
    /// 获取拼音的首字母
    /// - Returns: 拼音首字母
    func getPinYinFistStr()->String{
        let pinyin = self.toPinYin()
        return String(pinyin[pinyin.startIndex])
    }
    
    /// 字符串的匹配范围
    ///
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    @discardableResult
    func matchStrRange(_ matchStr: String) -> [NSRange] {
        var selfStr = self as NSString
        var withStr = Array(repeating: "X", count: (matchStr as NSString).length).joined(separator: "") //辅助字符串
        if matchStr == withStr { withStr = withStr.lowercased() } //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.range(of: matchStr).location != NSNotFound {
            let range = selfStr.range(of: matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.replacingCharacters(in: NSMakeRange(range.location, range.length), with: withStr) as NSString
        }
        return allRange
    }
    
    /// 匹配字符串中是否存在对应类型(比如：链接、电话、地址等)的字符串，并返回匹配的结果
    /// - Parameter checkingTypes: 对应要匹配的类型
    /// - Returns: 匹配的结果
    func matchesCheckingTypes(_ types:NSTextCheckingTypes = NSTextCheckingTypes(NSTextCheckingResult.CheckingType.link.rawValue)) -> [NSTextCheckingResult]?{
        let  dataDetector = try? NSDataDetector(types: types)
        let matchRes = dataDetector?.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, self.count))
        return matchRes
    }
    
    /// 匹配字符串中是否存在链接
    /// - Returns: 匹配结果
    func matchesCheckingLink() -> [NSTextCheckingResult]?{
        let regex = "(((https|http|ftps|ftp)://)([a-z0-9]+[.])|(www.))([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?([^# \\u4e00-\\u9fa5]*)?"//"((https|http|ftp|ftps):\/\/)([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?([\w-.:/?%&=]*)?"

        return self.matchesChecking(regex)
    }
    
    /// 正则匹配
    /// - Parameter regex: 正则表达式
    /// - Returns: 匹配结果
    func matchesChecking(_ regex:String)->[NSTextCheckingResult]?{
        let regularExpression = try? NSRegularExpression(pattern: regex, options: .caseInsensitive)
        let matchs = regularExpression?.matches(in: self, options: .reportProgress, range: NSRange(location: 0, length: self.count))
        return matchs
    }
    
    /// range转换为NSRange
     func nsRange(from range: Range<String.Index>) -> NSRange {
         return NSRange(range, in: self)
     }
    
    /// 使用下标截取字符串 例: "示例字符串"[0..<2] 结果是 "示例"
    subscript (r: Range<Int>) -> String {
        get {
            if (r.lowerBound > count) || (r.upperBound > count) { return "截取超出范围" }
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return String(self[startIndex..<endIndex])
        }
    }
}

extension NSAttributedString{
    
    /// 动态计算字体的Size
    /// - Parameters:
    ///   - size: 限定的大小
    /// - Returns: 字体大小
    func calculateTextSize(size:CGSize) ->CGSize{
                
        //动态计算字体宽度
        let rect = self.boundingRect(with: size,
                                     options: [.usesLineFragmentOrigin,
                                               .usesFontLeading,
                                               .truncatesLastVisibleLine],
                                     context: nil)
        return rect.size
    }
}
